var Global = require("../util/global.js");
var websocket = require("../util/websocket.js");
var http = require("../util/http.js");
var message = require("../util/message.js");

cc.Class({
    extends: cc.Component,

    properties: {
        bg:{
            type:cc.Sprite,
            default:null,
        },
        userList:{
            type: cc.ScrollView,
            default:null,
        },
        userItem:{
            type:cc.Prefab,
            default:null,
        },
        alert:{
            type:cc.Layout,
            default:null,
        },
        tip:{
            type:cc.Label,
            default:null,
        },
        uname:{
            type:cc.EditBox,
            default:null,
        },
        toUid:0,
        isRequest:false,
        refreshThread:null,
    },

    // onLoad () {},

    start () {
        this.init();
    },
    /**
     * 初始化游戏
     * @return {[type]} [description]
     */
    init(){
        cc.log("初始化游戏");

        this.initData();
        this.initUser();
        this.initWebSocket();
        this.initUserList();
        this.hideAlert();
        this.showTip("欢迎");
        //this.refreshUserList();
    },
    /**
     * 初始化数据
     * @return {[type]} [description]
     */
    initData(){
        //不显示调试信息
        cc.debug.setDisplayStats(false);

        //背景旋转
        this.bg.node.runAction(cc.repeatForever(cc.rotateBy(100,360)));

        //重置websocket
        if(Global.socket){
            Global.socket.sock.parent = this;
            Global.socket.sock.onmessage = this.onMessage;
        }
    },
    /**
     * 初始化用户
     * @return {[type]} [description]
     */
    initUser(){
        cc.log("初始化用户");

        Global.uid = localStorage.getItem("uid");
        Global.uname = localStorage.getItem("uname");

        if(!Global.uid){
            Global.uid = Math.ceil(Math.random()*900000)+100000;
            localStorage.setItem("uid",Global.uid);
        }
        if(!Global.uname){
            Global.uname = "用户"+Global.uid;
        }

        //初始化消息
        message.user.uid = Global.uid;
        message.user.uname = Global.uname;

        //初始化编辑框
        this.uname.getComponent(cc.EditBox).string = Global.uname;
    },
    /**
     * 保存用户名
     * @return {[type]} [description]
     */
    saveUname(){
        cc.log("保存用户名");

        var uname = this.uname.getComponent(cc.EditBox).string;
        Global.uname = uname;
        localStorage.setItem("uname",uname);

        message.type = 66;
        message.content = uname;
        websocket.sendData(message);
    },
    /**
     * 初始化websocket
     * @return {[type]} [description]
     */
    initWebSocket(){
        cc.log("初始化websocket");

        if(!Global.socket){
            var websocketUrl = Global.wsUrl+'/game/{uid}/{uname}';
            websocketUrl = websocketUrl.replace('{uid}',Global.uid);
            websocketUrl = websocketUrl.replace('{uname}',Global.uname);
            Global.socket = websocket.connect(websocketUrl,this);
            Global.socket.sock.onmessage = this.onMessage;
        }
    },
    /**
     * 初始化在线用户
     * @return {[type]} [description]
     */
    initUserList(){
        cc.log("初始化在线用户");
        
        var self = this;
        http.get(Global.apiUrl+'/user/list/'+Global.uid,function(json){
            self.userList.content.removeAllChildren();
            for(var i =0;i<json.data.length;i++){
                var user = json.data[i];
                var userItem = cc.instantiate(self.userItem);
                userItem.getChildByName('user').getComponent(cc.Label).string = user.uname;
                //是否游戏中,游戏中禁用按钮
                if(user.gaming){
                    userItem.getChildByName('start').getComponent(cc.Button).interactable = false;
                    userItem.getChildByName('start').getChildByName('Label').getComponent(cc.Label).string = "游戏中";
                }else{
                    self.bindClickEvent(userItem.getChildByName('start').getComponent(cc.Button),user.uid);
                }
                self.userList.content.addChild(userItem);
            }
        });
    },
    /**
     * 刷新用户列表
     * @return {[type]} [description]
     */
    refreshUserList(){
        cc.log("刷新在线用户");

        var self = this;
        self.refreshThread = setInterval(function(){
            self.initUserList();
        },3000);
    },
    /**
     * 挑战用户按钮绑定事件
     * @param  {[type]} button [description]
     * @param  {[type]} uid    [description]
     * @return {[type]}        [description]
     */
    bindClickEvent: function (button, uid) {
       cc.log("按钮绑定事件-挑战用户:"+uid);

       var clickEventHandler = new cc.Component.EventHandler();
       //这个 node 节点是你的事件处理代码组件所属的节点
       clickEventHandler.target = this.node; 
       //这个是代码文件名
       clickEventHandler.component = "start";
       clickEventHandler.handler = "onRequestFight";
       clickEventHandler.customEventData = uid;
       button.clickEvents.push(clickEventHandler);
    },
    /**
     * websocket接收消息
     * @param  {[type]} result [description]
     * @return {[type]}        [description]
     */
    onMessage(result){
        cc.log("接收消息:" + result.data);
        
        var self = this.parent;

        var message = JSON.parse(result.data);

        if(message.type==1){
            cc.log("敌方请求战斗");

            //弹框是否接受战斗
            self.showAlert();
            //修改对手
            Global.toUid = message.user.uid;
            Global.toUname = message.user.uname;
        }else if(message.type==2){
            cc.log("敌方接受战斗");

            self.showTip("对方接受邀请");

        }else if(message.type==3){
            cc.log("敌方拒绝战斗");

            self.isRequest = false;

            self.showTip("对方拒绝邀请");
        }else if(message.type==21){
            cc.log("接收题目:"+JSON.stringify(message.content));

            Global.bullets = message.content;

            if(self.isRequest){
                Global.toUid = message.user.uid;
                Global.toUname = message.user.uname;
            }
            clearInterval(self.refreshThread);
            cc.director.loadScene('ready');
        }
    },
    /**
     * 开始游戏
     * @param  {[type]} target [description]
     * @param  {[type]} uid    [description]
     * @return {[type]}        [description]
     */
    onRequestFight(target,uid){
        cc.log("请求战斗");

        message.toUid = uid;
        message.type = 1;
        message.content = "请求战斗";
        websocket.sendData(message);

        //请求战斗状态,方便区分敌我
        this.isRequest=true;
    },
    /**
     * 接受战斗
     * @return {[type]} [description]
     */
    onAcceptFight(){
        cc.log("接受战斗");

        message.toUid = Global.toUid;
        message.type = 2;
        message.content = "接受战斗";
        websocket.sendData(message);
        this.hideAlert();
    },
    /**
     * 拒绝战斗
     * @return {[type]} [description]
     */
    onRejectFight(){
        cc.log("拒绝战斗");

        message.toUid = Global.toUid;
        message.type = 3;
        message.content = "拒绝战斗";
        websocket.sendData(message);
        this.hideAlert();
    },
    /**
     * 显示弹框
     * @return {[type]} [description]
     */
    showAlert(){
        cc.log("显示弹框");

        this.alert.node.active = true;
    },
    /**
     * 隐藏弹框
     * @return {[type]} [description]
     */
    hideAlert(){
        cc.log("隐藏弹框");

        this.alert.node.active = false;
    },
    /**
     * 显示提示内容
     * @param  {[type]} content [description]
     * @return {[type]}         [description]
     */
    showTip(content){
        var self = this;
        this.tip.getComponent(cc.Label).string = content;
        this.tip.node.active = true;
        setTimeout(function(){
            if(self.tip)self.tip.node.active = false;
        },1000);
    }

    // update (dt) {},
});
